package com.cssw.fyzb.tps.service.res.adapter;

import com.cssw.fyzb.tps.config.res.CosConfiguration;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 腾讯云 对象存储 适配器
 *
 * @author Feng Chen
 */
public class CosAdapter implements ResAdapter {

    private CosConfiguration configuration;

    public CosAdapter(CosConfiguration configuration) {
        this.configuration = configuration;
    }

    private COSClient client;

    @Override
    public String upload(String dest, String contentType, byte[] content) {
        InputStream input = new ByteArrayInputStream(content);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(content.length);
        objectMetadata.setContentType(contentType);
        PutObjectRequest request = new PutObjectRequest(configuration.getBucketName(), dest, input, objectMetadata);
        client.putObject(request);
        return String.format(
                configuration.getUrlFormat(),
                configuration.getBucketName(),
//                configuration.getRegion(),
                dest
        );
    }

    @Override
    public void start() {
        if (client != null) {
            return;
        }

        COSCredentials cred = new BasicCOSCredentials(configuration.getSecretId(), configuration.getSecretKey());
        ClientConfig options = new ClientConfig();
        options.setRegion(new Region(configuration.getRegion()));
        options.setConnectionTimeout(configuration.getConnectionTimeout());
        options.setSocketTimeout(configuration.getSocketTimeout());
        client = new COSClient(cred, options);
    }

    @Override
    public void close() {
        if (client != null) {
            client.shutdown();
        }
    }
}
